using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace WpfTreeGridTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        
        private void TreeView_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e.HorizontalChange != 0)
            {
                var headerScrollViewer = FindVisualChild<ScrollViewer>(this);
                if (headerScrollViewer != null)
                {
                    headerScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
                }
            }
        }

        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }

        private void Thumb_OnDragCompleted(object sender, DragCompletedEventArgs e)
        {
            if (!(sender is Thumb thumb)) return;
            var tempParent = VisualTreeHelper.GetParent(thumb);
            if (tempParent == null || !(VisualTreeHelper.GetParent(tempParent) is Border c)) return;
            var width = (double.IsNaN(c.Width) ? c.ActualWidth : c.Width) + e.HorizontalChange;
            c.Width = Math.Max(width, c.MinWidth);
        }
    }
}